package com.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.example.service.impl.TraceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.StringReader;
import java.util.concurrent.TimeUnit;
@RefreshScope  // 配置动态刷新
@RestController
public class SentinelController {
    @RequestMapping("/sentinel1")
    public String sentinel1() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "sentinel1";
    }

    @RequestMapping("/sentinel2")
    public String sentinel2() {
        return "测试高并发下的问题";
    }


    @RequestMapping("/vip")
    public String vip() {
        return "vip";
    }

    @RequestMapping("/comm")         // 对外的接口默认就是资源
    public String comm() {
        return "comm";
    }

    @Autowired
    private TraceService traceService;

    @RequestMapping("/trace1")
    public void trace1(){
        traceService.vipResource();
    }

    @RequestMapping("/trace2")
    public void trace2(){
        traceService.vipResource();
    }

    @RequestMapping("/trace3")
    public void trace3(){
        traceService.vipResource();
    }

    int i=0;
    @RequestMapping("/fallBack2")
    public String fallBack2(){
        //模拟出现异常，异常比例为33%
        if(++i % 3 == 0) {
            throw new RuntimeException();
        }
        return "fallBack2";
    }

    @SentinelResource("product")
    @RequestMapping("/product")
    public String product(Long pid){
        return "商品：" + pid;
    }

    @RequestMapping("/authority")
    public String authority(){
        return "访问成功";
    }
    @RequestMapping("/showname")
    public String showname() {
        return "访问成功";
    }

    @Value("${globalConfig.title}")
    private String title;
    @RequestMapping("/showtitle")
    public String showTitle(){
        return title;
    }
}
